<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <div class="row_div">
        选择商品分类：
        <el-cascader
          v-model="cateKeys"
          :options="cateList"
          :props="CateProps"
          clearable
          @change="cateChange"
        ></el-cascader>
      </div>

      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="动态参数"
          name="many"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="paramsDialogVisible = true"
          >添加参数</el-button>
          <!-- 动态参数 表格 -->
          <el-table
            :data="manyData"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- {{ scope.row.attr_vals }} -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(item,scope.row)"
                >
                  >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column
              type="index"
              label="#"
            ></el-table-column>

            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>

            <el-table-column
              prop="date"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row)"
                >删除</el-button>
              </template>

            </el-table-column>

          </el-table>

        </el-tab-pane>
        <el-tab-pane
          label="静态属性"
          name="only"
        >
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="paramsDialogVisible = true"
          >添加属性</el-button>

          <!-- 静态属性 表格 -->
          <el-table
            :data="onlyData"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- {{ scope.row.attr_vals }} -->
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(item,scope.row)"
                >
                  >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column
              type="index"
              label="#"
            ></el-table-column>

            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>

            <el-table-column
              prop="date"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParam(scope.row)"
                >删除</el-button>
              </template>

            </el-table-column>

          </el-table>

        </el-tab-pane>
      </el-tabs>

    </el-card>

    <!-- 添加参数/添加属性 弹窗 -->
    <el-dialog
      :title="'添加'+paramsDialogText"
      :visible.sync="paramsDialogVisible"
      width="50%"
      @close="hideParamsDialog('addParamsFormRef')"
    >
      <!-- 内容 B -->
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="paramsDialogText"
          prop="attr_name"
        >
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 内容 E -->

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="paramsDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addParams('addParamsFormRef')"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数/属性 弹窗 -->
    <el-dialog
      :title="'修改'+paramsDialogText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="hideParamsDialog('editParamsFormRef')"
    >
      <!-- 内容 B -->
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item
          :label="paramsDialogText"
          prop="attr_name"
        >
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 内容 E -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editParams('editParamsFormRef')"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      token: '',
      CateProps: { // 商品分类 显示规则
        'expandTrigger': 'hover',
        'label': 'cat_name',
        'value': 'cat_id',
        'children': 'children'
      },
      cateKeys: [],
      cateList: [], // 商品分类数据列表
      activeName: 'many',
      manyData: [], // 动态参数数据
      onlyData: [], // 静态属性数据,
      paramsDialogVisible: false,
      addParamsForm: {
        'attr_name': ''
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑
      editDialogVisible: false,
      editParamsForm: {
        'attr_name': ''
      },
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    this.token = window.sessionStorage.getItem('token')
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$axios.get('categories', {
        params: { type: 3 },
        headers: { 'Authorization': this.token }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res)
      this.cateList = res.data
    },
    async cateChange() {
      if (this.cateKeys.length !== 3) {
        this.cateKeys = []
        this.manyData = []
        this.onlyData = []
        return
      }
      this.getParamsCateList()
    },
    handleClick(tab) {
      this.getParamsCateList()
    },
    async getParamsCateList() {
      if (!this.cateId) return
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          'sel': this.activeName
        },
        headers: { 'Authorization': this.token }
      })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制标签的不显示隐藏
        item.inputVisible = false
        // 控制标签的输入框
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyData = res.data
      } else {
        this.manyData = res.data
      }
    },
    // 关闭弹窗
    hideParamsDialog(formName) {
      this.$refs[formName].resetFields()
    },
    // 添加参数/属性
    addParams(formName) {
      this.$refs[formName].validate(async (valid) => {
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          'attr_name': this.addParamsForm.attr_name,
          'attr_sel': this.activeName
        }, {
          headers: {
            'Authorization': this.token
          }
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        this.$message.success('添加参数成功')
        this.paramsDialogVisible = false
        this.getParamsCateList()
      })
    },
    // 点击 修改参数/属性
    editParams(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          'attr_name': this.editParamsForm.attr_name,
          'attr_sel': this.activeName
        }, {
          headers: {
            'Authorization': this.token
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getParamsCateList()
        this.editDialogVisible = false
      })
    },
    showEditDialog(data) {
      console.log(data)
      this.editDialogVisible = true
      this.editParamsForm = data
    },
    // 删除
    async removeParam(data) {
      console.log(data)
      const reAttrId = data.attr_id
      console.log('点击了删除', reAttrId)
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 用户取消删除操作
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除!')
      }
      // 删除的业务逻辑
      const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${reAttrId}`, {
        headers: { 'Authorization': this.token }
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getParamsCateList()
    },
    // 标签
    handleClose(tag, row) {
      row.attr_vals.splice(row.attr_vals.indexOf(tag), 1)
      this.saveAttrVals(row)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveAttrVals(row) {
      const { data: res } = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          'attr_name': row.attr_name,
          'attr_sel': row.attr_sel,
          'attr_vals': row.attr_vals.join(' ')
        },
        { headers: { 'Authorization': this.token } }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(row.attr_sel === 'only' ? '更新静态属性失败' : '更新动态参数失败')
      }
      this.$message.success(row.attr_sel === 'only' ? '更新静态属性成功' : '更新动态参数成功')
    },
    async handleInputConfirm(row) {
      console.log(row)
      let inputValue = row.inputValue
      if (inputValue.trim()) {
        row.attr_vals.push(inputValue)
      }
      row.inputVisible = false
      row.inputValue = ''
      this.saveAttrVals(row)
    }
  },
  computed: {
    // 如果按钮需要被禁用，则返回true
    isBtnDisabled() {
      if (this.cateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 三级商品的id
    cateId() {
      if (this.cateKeys.length === 3) {
        return this.cateKeys[2]
      }
      return null
    },
    // 参数弹窗的title
    paramsDialogText() {
      if (this.activeName === 'only') {
        return '静态属性'
      }
      return '动态参数'
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  .row_div {
    margin: 20px 0 15px;
  }

  .el-tag + .el-tag {
    margin: 10px;
  }
  .button-new-tag {
    margin: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 120px;
    margin: 10px;
    vertical-align: bottom;
  }
}
</style>